package com.scnu.edu.controller;

import com.scnu.edu.entity.Movie;
import com.scnu.edu.entity.Rating;
import com.scnu.edu.entity.User;
import com.scnu.edu.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/movie")
public class CommentController {
    @Autowired
    private MovieService movieService;


    @Autowired
    private RatingService ratingService;

    @PostMapping("/comment")
    public String comment(@RequestParam Long movieId,
                          @RequestParam Double score,
                          @RequestParam String comment,
                          HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }

        Rating rating = new Rating();
        rating.setMovieId(movieId);
        rating.setUserId(user.getId());
        rating.setScore(score);
        rating.setComment(comment);
        rating.setCreateTime(new Date());
        rating.setUpdateTime(new Date());

        ratingService.save(rating);

        // 更新电影的平均评分
        updateMovieScore(movieId);

        return "redirect:/movie/detail?id=" + movieId;
    }

    private void updateMovieScore(Long movieId) {
        List<Rating> ratings = ratingService.getRatingsByMovieId(movieId);
        if (!ratings.isEmpty()) {
            double avgScore = ratings.stream()
                    .mapToDouble(Rating::getScore)
                    .average()
                    .orElse(0.0);
            Movie movie = movieService.getById(movieId);
            movie.setScore(avgScore);
            movieService.updateById(movie);
        }
    }

}
